package mao.thinkinjava.concurency.threadlocal;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * @author Totoro
 * @date 2020/5/11 14:53
 */
public class Access implements Runnable {
    private int id;
    public Access(int id){
        this.id = id;
    }
    @Override
    public void run() {
        while (!Thread.currentThread().isInterrupted()){
            ThreadLocalVariableHolder.increment();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(this);
        }
    }

    @Override
    public String toString() {
        return "Access{" +
                "id=" + id +
                '}'+ThreadLocalVariableHolder.get();
    }

    public static void main(String[] args) {
        ExecutorService exe = Executors.newCachedThreadPool(new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                //thread.isInterrupted();
                thread.setDaemon(true);
                return thread;
            }
        });
        for (int i = 0; i < 10; i++) {
            exe.execute(new Access(i));
        }
        exe.shutdown();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Thread.interrupted();
    }
}
